package com.example.crm.config;

import com.example.crm.entity.Right;
import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.service.IUserService;
import javax.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;
import java.util.Set;


public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShiroRealm.doGetAuthenticationInfo获取身份信息!");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
        User user=userService.getUserByName(userName);
        if(user==null){
            throw new UnknownAccountException();
        }
        if(user.getUsrFlag()==null || user.getUsrFlag()==0){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getUsrPassword(),
                getName()
        );
        return info;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用MyShiroRealm.doGetAuthorizationInfo获取授权信息!");
        User user=(User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//        静态授权:授予主体相应的角色和权限
//        info.addRole(user.getRole().getRoleName());
//        info.addStringPermission("用户列表");
//        if("管理员".equals(user.getRole().getRoleName())){
//            info.addStringPermission("用户添加");
//            info.addStringPermission("用户编辑");
//            info.addStringPermission("用户删除");
//        }
        //动态授权
        Role role=user.getRole();
        if(role != null){
            info.addRole(user.getRole().getRoleName());
            List<Right> rightSet=role.getRights();
            if(rightSet !=null && rightSet.size()>0){
                for (Right right:rightSet){
                    info.addStringPermission(right.getRightCode());
                }
            }
        }
        return info;
    }
}
